package runtime

import (
	"context"
	"log"
	"os"
	"os/signal"
	"syscall"

	"torler.com/qingyue/pkg/logger"
)

type RuntimeManager struct {
	name    string
	servers []Server
}

// 创建运行时管理器
// 用于统一管理所有服务
func NewServer(name string) *RuntimeManager {
	return &RuntimeManager{
		name:    name,
		servers: []Server{},
	}

}

// 添加服务
func (a *RuntimeManager) Add(server Server) {
	a.servers = append(a.servers, server)
}

func (a *RuntimeManager) Run(ctx context.Context) error {
	var cancel context.CancelFunc
	ctx, cancel = context.WithCancel(ctx)
	defer cancel()

	signals := make(chan os.Signal, 1)
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)

	for _, srv := range a.servers {
		go func(srv Server) {

			err := srv.Start(ctx)
			if err != nil {
				log.Printf("Server start err: %v", err)
			}

		}(srv)
		logger.Default().Info("成功启动服务: " + srv.Name())
	}

	select {
	case <-signals:
		// Received termination signal
		log.Println("Received termination signal")
	case <-ctx.Done():
		// Context canceled
		log.Println("Context canceled")
	}

	// Gracefully stop the servers
	for _, srv := range a.servers {
		err := srv.Stop(ctx)
		if err != nil {
			log.Printf("Server stop err: %v", err)
		}
	}

	return nil
}
